package Leetcode增强计划;

import java.util.*;

/**
 * @author : K k
 * @date : 17:23 2020/10/17
 */
public class 二叉树的锯齿形层次遍历_103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        boolean flag = true;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            LinkedList<Integer> path = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.pollFirst();
                if(node !=null){
                    if(flag){
                        path.addFirst(node.val);
                    }else {
                        path.addLast(node.val);
                    }

                    if (node.left != null)
                        queue.addLast(node.left);
                    if (node.right != null)
                        queue.addLast(node.right);
                }
            }
            flag=!flag;
            res.add(path);
        }
        return res;
    }

    public static void main(String[] args) {
        
    }
}
